#include "app_pool.h"
#include "log/log.h"
#include <pthread.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <mqueue.h>
static  pthread_t *thread_pool;
static  int thread_num;
static char *mq_name = "/task_mq";
static mqd_t mq_fd;

static void *thread_func(void *arg)
{
    Task task;
    while (1)
    {
        ssize_t len = mq_receive(mq_fd, (char *)&task, sizeof(Task), NULL);
        if (len == sizeof(Task))
        {
            task.task_func(task.arg);
        }
        
    }  
}

int app_pool_init(int num)
{
    thread_num = num;
    thread_pool = malloc(sizeof(pthread_t) * num);
    for (int i = 0; i < num; i++)
    {
        pthread_create(&thread_pool[i], NULL, thread_func, NULL);
    }
    
    struct mq_attr attr;
    attr.mq_maxmsg = 10;
    attr.mq_msgsize = sizeof(Task);
    
    mq_fd = mq_open(mq_name, O_CREAT | O_RDWR, 0644, &attr);
    
    if (mq_fd == -1)
    {
        log_error("mq_open error");
        return -1;
    }
    log_debug("线程池初始化成功");
    
    return 0;
}

void app_pool_destroy()
{
    for (int i = 0; i < thread_num; i++)
    {
        pthread_cancel(thread_pool[i]);
        pthread_join(thread_pool[i], NULL);
    }
    free(thread_pool);

    mq_close(mq_fd);
    mq_unlink(mq_name);
}

int app_pool_registerTask(int (*task_func)(void *arg),void *arg)
{
    Task task = {
        .task_func = task_func,
        .arg = arg
    };
    
    return mq_send(mq_fd, (char *)&task, sizeof(Task), 1);
}
